package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.common.Callback.CancelledException;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.ModelAdapter;
import com.dotstone.chipism.adapter.ModelAdapter1;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.ModelSort;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.CharacterParser;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.KeyManager;
import com.dotstone.chipism.util.MsgCode;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.PinyinModelComparator;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.ClearEditText;
import com.dotstone.chipism.view.SideBar;
import com.dotstone.chipism.view.SideBar.OnTouchingLetterChangedListener;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.tiqiaa.client.IRemoteClient;
import com.tiqiaa.client.IRemoteClient.CallBackOnRemoteDownloaded;
import com.tiqiaa.client.IRemoteClient.CallbackOnSearchDone;
import com.tiqiaa.client.impl.RemoteClient;
import com.tiqiaa.icontrol.util.LanguageUtils;
import com.tiqiaa.ircode.impl.InfraredFetcher;
import com.tiqiaa.irdnasdk.IrDnaSdkHelper;
import com.tiqiaa.remote.IRemoteManager;
import com.tiqiaa.remote.entity.AirMode;
import com.tiqiaa.remote.entity.AirPower;
import com.tiqiaa.remote.entity.AirRemoteState;
import com.tiqiaa.remote.entity.AirTemp;
import com.tiqiaa.remote.entity.AirWindAmount;
import com.tiqiaa.remote.entity.Infrared;
import com.tiqiaa.remote.entity.Key;
import com.tiqiaa.remote.entity.Page;
import com.tiqiaa.remote.entity.Remote;
import com.tiqiaa.remote.impl.RemoteManager;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ModelSelectionActivity1 extends BaseActivity implements CallbackOnSearchDone {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private TextView mTitleTv;
	private long brandId;
	private String brand;
	private int type;
	private String appliance;
	private List<Remote> rs = new ArrayList<Remote>();
	private List<ModelSort> modelSorts = new ArrayList<ModelSort>();
	private ListView mModelLv;
	// private RemoteClient rc;
	private Page page;
	private ModelAdapter1 modelAdapter;
	private SVProgressHUD mSVProgressHUD;
	private IRemoteClient client;
	private ModelSelectionActivity1 modelSelectionActivity1;
	private CharacterParser characterParser;
	private SideBar sideBar;
	private ClearEditText mClearEditText;
	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinModelComparator pinyinComparator;
	private Dialog dialog;
	private Button cancel_btn;
	private Button ensure_btn;
	private boolean done = false;
	private String deviceId;
	private Remote currentRemote;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MsgCode.TIME_OUT:
				if (deviceId == null) {
					ToastShow.Show(getApplicationContext(), "保存失败，请重试");
					if (mSVProgressHUD.isShowing()) {
						mSVProgressHUD.dismiss();
					}
				} else {
					deleteDevice();
				}
				break;

			default:
				break;
			}
		}
	};

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_model_selection;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		modelSelectionActivity1 = this;
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mTitleTv = $(R.id.title_tv);
		mModelLv = $(R.id.model_lv);
		mTitleTv.setVisibility(View.VISIBLE);
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinModelComparator();
		type = getIntent().getIntExtra("type", 999);
		brand = getIntent().getStringExtra("brand");
		brandId = getIntent().getLongExtra("brandId", 999);
		appliance = Util.getAppliance(getApplicationContext(), type);
		mTitleTv.setText(brand + ": 型号 选择（DIY库）");
		client = new RemoteClient(ModelSelectionActivity1.this);
		initModel();
		boolVersion();
		sideBar = (SideBar) findViewById(R.id.sidrbar);
		mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);
		mBackL.setOnClickListener(this);
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = modelAdapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					mModelLv.setSelection(position);
				}

			}
		});
		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		mModelLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int p, long arg3) {
				// TODO Auto-generated method stub
				// Remote r = rs.get(p);
				currentRemote = rs.get(p);
				ModelSort m = modelAdapter.getAdapterData().get(p);
				Log.i("wmy", type + "点击了 = " + m.getRemoteId());
				boolean e = DeviceManager.getInstance().checkName(appliance + " " + brand + " " + m.getModel());
				if (e) {
					// 该名字的遥控器已经存在
					ToastShow.Show(getApplicationContext(), "已添加该型号遥控器");
					return;
				}
				showConfirmDialog(m);
			}
		});
	}

	private void showConfirmDialog(final ModelSort m) {
		dialog = new Dialog(ModelSelectionActivity1.this);
		dialog.setContentView(R.layout.dialog_confirm_respond);
		TextView remind_tv = (TextView) dialog.findViewById(R.id.remind_tv);
		remind_tv.setText("名称" + brand + appliance + " 型号：" + m.getModel() + "\n" + "是否下载该遥控器数据？");
		cancel_btn = (Button) dialog.findViewById(R.id.cancel_btn);
		cancel_btn.setText("取消");
		ensure_btn = (Button) dialog.findViewById(R.id.ensure_btn);
		ensure_btn.setText("确定");
		cancel_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		ensure_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				client.download_reomte(m.getRemoteId(), new CallBackOnRemoteDownloaded() {

					@Override
					public void onRemoteDownloaded(int errcode, final Remote remote) {
						if (errcode != CallBackOnRemoteDownloaded.ERROR_CODE_SUCCESS) {
							Toast.makeText(getApplicationContext(), "下载遥控器失败", Toast.LENGTH_SHORT).show();
							return;
						} else {
							currentRemote = remote;
							IRemoteManager manager = new RemoteManager();
							manager.addRemote(remote);
							save();
							checkTimeOut();
						}
					}
				});
			}
		});
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}

	private void checkTimeOut() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(10000);
					if (!done) {
						mHandler.sendEmptyMessage(MsgCode.TIME_OUT);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
		;

	}

	private void deleteDevice() {
		if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (mSVProgressHUD.isShowing()) {
				mSVProgressHUD.dismiss();
			}
			ToastShow.Show(getApplicationContext(), "没有网络");
			return;
		}
		RequestParams params = new RequestParams(HttpURL.DELETE_DEVICE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("deviceId", deviceId);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.d("Tag", "delete device " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("test", "delete =" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String resultCode = jsonObject.getString("resultCode");
					deviceId = null;
					mHandler.sendEmptyMessage(MsgCode.TIME_OUT);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}
		});
	}

	private void save() {
		mSVProgressHUD = new SVProgressHUD(ModelSelectionActivity1.this);
		mSVProgressHUD.showWithStatus("正在保存");
		// 上传设备
		RequestParams params = new RequestParams(HttpURL.UPLOAD_DEVICE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {

			obj.put("classification", "4");
			obj.put("key", "10000");
			obj.put("deviceModel", currentRemote.getId());
			obj.put("deviceName", appliance + " " + brand + " " + currentRemote.getModel());
			if (type == DeviceType.DEVICE_TYPE_BOX) {
				obj.put("deviceType", DeviceType.DEVICE_TYPE_BOX2 + "");
			} else {
				obj.put("deviceType", type + "");
			}
			obj.put("deviceVersion", "3.1.0");
			obj.put("deviceWifiSSID", currentRemote.getId().equals("") ? "未知" : currentRemote.getId());
			obj.put("deviceId", "0");
			obj.put("productId", "4");
			obj.put("mainDeviceId", DeviceManager.getInstance().getmWlanId());
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.i("wmy", " upload remote obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "upload remote result = " + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						deviceId = jsonObject.getString("data");
						// 获取deviceId之后 上传所有按键
						uploadKeys();
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void uploadKeys() {
		// 上传空调按键
		String buttonCmdS = "";
		String positionS = "";
		String nameS = "";
		List<com.dotstone.chipism.bean.Key> keys = new ArrayList<com.dotstone.chipism.bean.Key>();
		List<Key> remoteKeys = currentRemote.getKeys();
		Log.i("wmy", "541 uploadKeys remote.getKeys() = " + currentRemote.getKeys().size());
		for (int i = 0; i < remoteKeys.size(); i++) {
			com.dotstone.chipism.bean.Key key = new com.dotstone.chipism.bean.Key();
			key.setKeyNum(remoteKeys.get(i).getType());
			// InfraredFetcher mFetcher = new
			// InfraredFetcher(getApplicationContext());
			// Log.i("wmy", "remoteKeys.get(i).getType() = " +
			// remoteKeys.get(i).getType());
			// List<Infrared> infrareds = mFetcher.fetchInfrareds(currentRemote,
			// remoteKeys.get(i));
			List<Infrared> infrareds = remoteKeys.get(i).getInfrareds();
			Log.i("wmy", "remoteKeys.get(i).getType() = " + remoteKeys.get(i).getType() + " infrareds.size() = "
					+ infrareds.size());
			byte[] data = IrDnaSdkHelper.getIrCode(infrareds.get(0).getFreq(), infrareds.get(0).getData());
			String str = Util.bytesToHexString(data).toUpperCase();
			Log.i("wmy", "获取按键 " + key.getKeyId() + " " + str);
			key.setCodeValue(str);
			keys.add(key);
		}
		Log.e("wmy", "280 upload keys.size() = " + keys.size());
		for (int i = 0; i < keys.size(); i++) {
			if (keys.get(i).getKeyNum() != 811 && keys.get(i).getKeyNum() != 812 && keys.get(i).getKeyNum() != 832
					&& keys.get(i).getKeyNum() != 833) {
				buttonCmdS += keys.get(i).getCodeValue() + ",";
				positionS += keys.get(i).getKeyNum() + ",";
				nameS += KeyManager.getInstance().getKeyNameById((int) keys.get(i).getKeyNum()) + ",";
			}
		}
		InfraredFetcher mFetcher1 = new InfraredFetcher(getApplicationContext());
		AirRemoteState mState1 = mFetcher1.getAirRemoteStatus(currentRemote);
		Log.e("wmy", "init tempkey = "+(mState1==null));
		if (mState1 != null) {
			for (int i = 16; i < 32; i++) {
				InfraredFetcher mFetcher = new InfraredFetcher(getApplicationContext());
				AirRemoteState mState = mFetcher.getAirRemoteStatus(currentRemote);

				List<Infrared> irList = mFetcher.fetchAirInfrareds(currentRemote, mState, AirPower.getPowerState(1),
						AirMode.getMode(4), mState.getWind_amount(), AirTemp.getAirTemp(i));
				Log.i("wmy", "根据度数 " + i + " 获取指令 = " + irList.size());
				if (irList.get(0) != null && irList.get(0).getData() != null) {
					byte[] data = IrDnaSdkHelper.getIrCode(irList.get(0).getFreq(), irList.get(0).getData());
					// String str = Util.bytesToHexString(data).toUpperCase();
					buttonCmdS += Util.bytesToHexString(data).toUpperCase() + ",";
					positionS += (10000 + i) + ",";
					nameS += KeyManager.getInstance().getKeyNameById((10000 + i)) + "度,";
				}
			}

			Log.e("wmy", "init modeKey");
			for (int i = 0; i < 5; i++) {
				InfraredFetcher mFetcher = new InfraredFetcher(getApplicationContext());
				AirRemoteState mState = mFetcher.getAirRemoteStatus(currentRemote);
				List<Infrared> irList = mFetcher.fetchAirInfrareds(currentRemote, mState, AirPower.getPowerState(1),
						AirMode.getMode(i), mState.getWind_amount(), AirTemp.getAirTemp(26));
				Log.i("wmy", "根据模式 " + i + " 获取指令 = " + irList.size());
				if (irList.get(0) != null && irList.get(0).getData() != null) {
					byte[] data = IrDnaSdkHelper.getIrCode(irList.get(0).getFreq(), irList.get(0).getData());
					buttonCmdS += Util.bytesToHexString(data).toUpperCase() + ",";
					if (i == 0) {
						positionS += "10205,";
						nameS += "自动,";
					} else if (i == 1) {
						positionS += "10201,";
						nameS += "送风,";
					} else if (i == 2) {
						positionS += "10204,";
						nameS += "抽湿,";
					} else if (i == 3) {
						positionS += "10203,";
						nameS += "取暖,";
					} else if (i == 4) {
						positionS += "10202,";
						nameS += "制冷,";
					}
				}
			}
			Log.e("wmy", "init windKey");
			for (int i = 0; i < 5; i++) {
				InfraredFetcher mFetcher = new InfraredFetcher(getApplicationContext());
				AirRemoteState mState = mFetcher.getAirRemoteStatus(currentRemote);
				List<Infrared> irList = mFetcher.fetchAirInfrareds(currentRemote, mState, AirPower.getPowerState(1),
						AirMode.getMode(4), AirWindAmount.getWindAmount(i), AirTemp.getAirTemp(26));
				Log.i("wmy", "根据风量 " + i + " 获取指令 = " + irList.size());
				if (irList.get(0) != null && irList.get(0).getData() != null) {
					byte[] data = IrDnaSdkHelper.getIrCode(irList.get(0).getFreq(), irList.get(0).getData());
					buttonCmdS += Util.bytesToHexString(data).toUpperCase() + ",";
					if (i == 0) {
						positionS += "10101,";
						nameS += "一档,";
					} else if (i == 1) {
						positionS += "10102,";
						nameS += "二档,";
					} else if (i == 2) {
						positionS += "10103,";
						nameS += "三档,";
					} else if (i == 3) {
						positionS += "10104,";
						nameS += "四档,";
					} else if (i == 4) {
						positionS += "10105,";
						nameS += "自动,";
					}
				}
			}
			InfraredFetcher mFetcher = new InfraredFetcher(getApplicationContext());
			AirRemoteState mState = mFetcher.getAirRemoteStatus(currentRemote);
			List<Infrared> irList = mFetcher.fetchAirInfrareds(currentRemote, mState, AirPower.getPowerState(0),
					mState.getMode(), mState.getWind_amount(), mState.getTemp());
			Log.i("wmy", "根据电源 ");
			if (irList.get(0) != null && irList.get(0).getData() != null) {
				byte[] data = IrDnaSdkHelper.getIrCode(irList.get(0).getFreq(), irList.get(0).getData());
				buttonCmdS += Util.bytesToHexString(data).toUpperCase() + ",";
				positionS += "4000,";
				nameS += "关闭,";
			}
		}
		if (buttonCmdS.length() > 1) {
			buttonCmdS = buttonCmdS.substring(0, buttonCmdS.length() - 1);
		}
		if (positionS.length() > 1) {
			positionS = positionS.substring(0, positionS.length() - 1);
		}
		if (nameS.length() > 1) {
			nameS = nameS.substring(0, nameS.length() - 1);
		}

		RequestParams params = new RequestParams(HttpURL.UPLOAD_REMOTE_KEY_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("buttonCmdS", buttonCmdS);
			obj.put("key", "10000");
			obj.put("positionS", positionS);
			obj.put("deviceId", deviceId);
			obj.put("nameS", nameS);
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.e("wmy", " upload key = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "upload key result=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						done = true;
						ToastShow.Show(getApplicationContext(), "保存成功");
						// KeyManager.getInstance().clear();
						// RemoteSelectionActivity.remoteSelectionActivity.finish();
						// DIYActivity.diyActivity.finish();
						// DIYActivity1.diyActivity1.finish();
						finish();
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void filterData(String filterStr) {
		Log.i("wmy", "过滤字段 = " + filterStr);
		List<ModelSort> filterDateList = new ArrayList<ModelSort>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = modelSorts;
		} else {
			filterDateList.clear();
			for (ModelSort sortModel : modelSorts) {
				String name = sortModel.getModel();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}
		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		Log.i("wmy", "filterDateList.size() = " + filterDateList.size());
		modelAdapter.updateListView(filterDateList);
	}

	private void initModel() {
		// rc = new RemoteClient(getApplicationContext());
		// 显示加载进度条
		mSVProgressHUD = new SVProgressHUD(this);
		mSVProgressHUD.showWithStatus("正在加载");
		page = new Page();
		page.setPage(0);
		page.setAppliance_type(type);
		page.setBrand_id(brandId);
		page.setKeyword("");
		page.setLang(LanguageUtils.getLang());
		Log.i("wmy", "LanguageUtils.getLang() = " + LanguageUtils.getLang() + " brandId = " + brandId + " " + type);
		// modelAdapter.clearRemotes();
		Log.e("wmy", "Locale.getDefault().toString() = " + Locale.getDefault().toString());
		search(page);
	}

	private void search(Page page) {
		// 通讯客户端
		IRemoteClient client = new RemoteClient(getApplicationContext());
		client.searchDiy(page, modelSelectionActivity1);
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void onSearchDone(int errcode, List<Remote> remotes) {
		// TODO Auto-generated method stub
		if (errcode == CallbackOnSearchDone.ERROR_CODE_FAILURE) {
			showToast("搜索失败");
		} else {
			if (remotes != null && remotes.size() > 0) {

				for (Remote r : remotes) {
					Log.e("wmy", "搜索到型号:" + " " + r.getModel() + " " + r.getKeys().size() + " " + r.getDown_count()
							+ " " + r.getDownload_count());
					rs.add(r);
				}
				// 当前搜索的页数再加一页 重新搜索
				page.setPage(page.getPage() + 1);
				search(page);
				Log.e("wmy", "换页" + page.getPage());
			} else {
				// showToast("无更多遥控器");
				// 取消进度条显示
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				for (int i = 0; i < rs.size(); i++) {
					Remote b = rs.get(i);
					// Log.i("wmy", b.getModel()+"下载次数 =
					// "+b.getDownload_count());
					ModelSort bsort = new ModelSort();
					bsort.setModel(b.getModel());
					if (b.getModel() != null) {
						String pinyin = characterParser.getSelling(b.getModel());
						if (pinyin.length() < 2) {
							bsort.setSortLetters("#");
						} else {
							String sortString = pinyin.substring(0, 1).toUpperCase();
							if (sortString.matches("[A-Z]")) {
								bsort.setSortLetters(sortString.toUpperCase());
							} else {
								bsort.setSortLetters("#");
							}
						}
					} else {
						bsort.setSortLetters("#");
					}
					bsort.setRemoteId(b.getId());
					bsort.setDownload_count(b.getDownload_count());
					modelSorts.add(bsort);
				}
				// Collections.sort(modelSorts, pinyinComparator);
				modelAdapter = new ModelAdapter1(getApplicationContext(), modelSorts, brand, type);
				mModelLv.setAdapter(modelAdapter);
			}
		}
	}

}
